import * as types from './mutation-types'
// import * as publics from './public'
export default{
  // 进入页面之前，先从数据库获取该用户的历史聊天记录
  [types.GET_DB_MESSAGE_LIST](state, data) {
    state.messageList1 = data
  },
  // 修改聊天列表
  [types.SET_MESSAGE_LIST](state, data) {
    /*
    已经将代码交由action文件里面处理
    console.log(data)
    // 对于发送消息，先遍历消息列表有没有过聊天信息，如果没有，就在聊天列表添加，如果有就更新与该好友的聊天项
    // 对于发送消息，id为发送消息的用户，对于接受到的消息，id为发送消息的用户进行查找
    // data:  {id: '',name: '', msg:{msg: '', time: num read  self:true}}
    console.log(state.messageList1, '11111111111')
    let tempitem = state.messageList1.filter(item => {
      // 这里的判断需要修改
      // console.log(item._id, data.id)
    if (item._id === data.id) {
        return item
      }
    })
    // console.log(tempitem)
    // 原先没有聊天过的，添加聊天用户进聊天列表
    if (tempitem.length === 0) {
      let tempcurrent = {}
      tempcurrent['_id'] = data.id
      tempcurrent['name'] = data.name
      tempcurrent['list'] = []
      tempcurrent['list'].push({...data.msg})
      // console.log(tempcurrent, '222222222')
      state.messageList1.push({...tempcurrent})
    } else {
      // console.log(tempitem[0].list, data.msg)
      // 原先有聊天过的，直接添加聊天消息
      tempitem[0].list.push(data.msg)
      // console.log(tempitem, '11111111111111')
    }
    console.log(state.messageList1, '33333333333')
    window.localStorage.setItem(state.currentLoginUser.username + 'user', JSON.stringify(state.messageList1))
    */
  },
  // 修改当前聊天的用户对象 data 1105181206098244#mini-chat_cwf17@easemob.com
  [types.SET_CURRENT_CHAT_USER](state, data) {
    // console.log(data)
    let obj = {'id': data}
    state.currentChatUserId = obj
    console.log('当前用户的id', state.currentChatUserId.id)
  },
  // 修改当前聊天用户的未读消息为0
  [types.RESET_MESSAGE_LIST_UNREADNUM](state, id) {
    // console.log('修改未读消息后的聊天列表', state.messageList1)
    let itemUser = state.messageList1.filter(item => {
      console.log('修改当前聊天用户的未读消息为0', item._id, id)
      if (item._id === id) {
        return item
      }
    })
    console.log(itemUser)
    if (itemUser.length) {
      itemUser[0].list.forEach(item => {
        if (!item.read) {
          item.read = !item.read
        }
      })
    }
    console.log('修改未读消息后的聊天列表', state.messageList1)
    // window.localStorage.setItem(state.currentLoginUser.username + 'user', JSON.stringify(state.messageList1))
  },
  // 修改当前登录的用户
  [types.SET_CURRENT_LOGIN_USER](state, user) {
    // console.log(state.currentLoginUser, user)
    if (!state.currentLoginUser.username || state.currentLoginUser.username !== user.username) {
      // console.log(2)
      state.currentLoginUser = {...user}
    } else if (state.currentLoginUser.username === user.username && ('headicon' in user)) {
      // console.log(1)
      state.currentLoginUser = {...user}
    }
  },
  // 当用户登录时设置当前用户的好友列表
  [types.SET_CURRENTUSER_FRIENDSLIST](state, data) {
    // console.log(friends, '////////////////////')
    // state.friends = []
    // console.log(state.friends, ']]]]]]]]') 欠缺一个初始化的考虑*******8
    // let name = JSON.parse(window.localStorage.getItem('currentLoginUsername')) || ''
    if (data.flag === '1') {
      // console.log(1)
      state.friends = [...data.friends]
    } else if (data.flag === '2') {
      // console.log(2)
      // state.friends = [...data.friends]
      data.friends.forEach(item => {
        let arr = state.friends.filter(f => f.name === item.name)
        if (!arr.length) {
          state.friends.push(item)
        }
      })
    }
    // state.friends = friends.filter(item => item.name !== 'undefined')
    console.log(state.friends, '初始化的好友列表')
    // jixugeng
  },
  // 删除当前用户的好友列表
  [types.DELETE_CURRENTUSER_FRIENDSLIST](state, jid) {
    // state.friends.splice(index, 1)
    state.friends = state.friends.filter(item => item.jid !== jid)
    console.log('vuex删除后的好友列表', state.friends)
  },
  // 用户添加好友，设置vuex里面的好友列表
  [types.ADD_CURRENTUSER_FRIENDSLIST](state, friendObj) {
    // console.log(friends, '////////////////////')
    // state.friends = []
    // console.log(state.friends, ']]]]]]]]')
    state.friends.push(friendObj)
    console.log(state.friends, 'vuex增加好友列表')
  },
  // 当用户登录时，获取收到所有的未读的消息 data：发过来的内容from：用户名谁发过来的delay:收到消息的时间 构建当前用户的所有消息列表
  [types.INIT_GETUNREAD_MESSAGE_LIST](state, data) {
    console.log(state.messageList1)
    // 删除一项再增加一项
    state.messageList1.splice(data.index, 1, data.obj)
    /*
    其余的代码交由action文件执行
    // 获取本地聊天列表记录数组
    // let localMessageList = JSON.parse(window.localStorage.getItem(state.currentLoginUser.username + 'user')) || []
    // // 该数据从数据里面获得
    // state.messageList1 = publics.cloneObj(localMessageList)
    // console.log('获取本地聊天列表记录数组赋值给vuex 【】', state.messageList1)
    console.log(Object.getOwnPropertyNames(message).length, '检测发送的消息列表是否为空')
    // 每一次在这里构建列表 当列表不为空，并且收到的消息也不是空的时候
    if (state.messageList1.length > 0 && Object.getOwnPropertyNames(message).length !== 0) {
       let tempitem = state.messageList1.filter(item => {
         if (item['name'] === message['from']) {
          //  console.log(item['name'], message.from, item.list)
          //  let list = publics.cloneObj(item.list)
          //  console.log(list)
          //  // let objmsg = {msg: message['data'], time: message.delay.getItem(), read: false, self: false}
          //  let time
          //  if (message.delay) {
          //     time = new Date(message.delay).getTime()
          //  } else {
          //     time = new Date().getTime()
          //  }
          //  console.log(time)
          //  list.push({msg: message['data'], time: time, read: false, self: false})
          //  console.log(list)
          //  delete item.list
          //  item.list = publics.cloneObj(list)
          //  console.log(item, '123123123')
           return item
         }
       })
      console.log(tempitem)
      if (tempitem.length <= 0) {
        console.log(1111111112)
        // 如果该消息列表还没有与该好友的聊天记录，字节将本次消息写入消息列表
        let obj = {}
        obj['_id'] = '1105181206098244#mini-chat_' + message['from'] + '@easemob.com'
        obj['name'] = message['from']
        obj['list'] = []
        let time
        if (message.delay) {
          time = new Date(message.delay).getTime()
        } else {
          time = new Date().getTime()
        }
        obj['list'].push({msg: message['data'], time: time, read: false, self: false})
        state.messageList1.push(obj)
        console.log(state.messageList1, '77777777777')
      } else {
        let time
        if (message.delay) {
          time = new Date(message.delay).getTime()
        } else {
          time = new Date().getTime()
        }
        console.log(time, '收到消息的时间')
        tempitem[0].list.push({msg: message['data'], time: time, read: false, self: false})
      }
      // console.log(tempitem)
    } else if (Object.getOwnPropertyNames(message).length !== 0) {
      let obj = {}
      obj['_id'] = '1105181206098244#mini-chat_' + message['from'] + '@easemob.com'
      obj['name'] = message['from']
      console.log(obj)
      obj['list'] = []
      let time
      if (message.delay) {
        time = new Date(message.delay).getTime()
      } else {
        time = new Date().getTime()
      }
      console.log(time, '收到消息的时间')
      obj['list'].push({msg: message['data'], time: time, read: false, self: false})
      state.messageList1.push(obj)
    }
    console.log('收到消息后的列表', state.messageList1)
    // 将数据存进数据库里面
    window.localStorage.setItem(state.currentLoginUser.username + 'user', JSON.stringify(state.messageList1))
    */
  },
  // 当用户登录时，前提条件是已经有了未读消息和好友列表，构建消息列表
  [types.INIT_MESSAGE_LIST](state, data) {
    // console.log(state.currentLoginUser.username)
    // 获取本地聊天列表记录数组
    // let localMessageList = JSON.parse(window.localStorage.getItem(state.currentLoginUser.username + 'user')) || []
    state.messageList1 = data
    console.log('获取本地聊天列表记录数组赋值给vuex 【】', state.messageList1)
    // 如果有未读的消息
    if (state.unreadList.length) {
      // 先找到发出消息用户的id，在从消息列表中搜索，是否有该用户，如果有，直接添加
        state.unreadList.forEach(item => {
          console.log(item)
          state.friends.forEach(iitem => {
            console.log(iitem, item.from, iitem.name)
            if (item.from === iitem.name) {
              item['_id'] = iitem['jid']
            }
          })
        })
        state.unreadList.forEach(item => {
          let tempitem = state.messageList1.filter(iitem => {
            if (item['_id'] === iitem['_id']) {
              return item
            }
          })
          // 如果该消息列表已经有该好友聊天记录，直接将消息并入该消息列表
          if (tempitem.length) {
            let objmsg = {msg: item['data'], time: item.delay.getItem(), read: false, self: false}
            tempitem[0].list.push(objmsg)
          } else {
            // 如果该消息列表还没有与该好友的聊天记录，字节将本次消息写入消息列表
            let obj = {}
            obj['_id'] = item['_id']
            obj['name'] = item['from']
            obj['list'] = []
            obj['list'].push({msg: item['data'], time: new Date(item.delay).getTime(), read: false, self: false})
            state.messageList1.push(obj)
          }
        })
      // console.log(state.messageList1, '111111111111111111111111111111111111')
    }
  },
  // 用户收到好友添加的请求时，修改vuex里面的数据，以便渲染更新
  [types.REVCIEVE_FRIENDS_POST](state, obj) {
    // 先判断该陌生人有没有发起过添加好友的请求
    // let tempitem = state.onPresenceFriends.find(f => f.from === message.from) || {}
    // console.log(tempitem, '888888888888888888888888888')
    // if (!Object.getOwnPropertyNames(tempitem).length) {
      if (!obj.resetFlag) {
        state.onPresenceFriends.push(obj.message)
      } else {
        let index = state.onPresenceFriends.findIndex((item, i) => {
          // if (item.fromJid === obj.message.fromJid) {
            return item.fromJid === obj.message.fromJid
          // }
        })
        console.log(index)
        state.onPresenceFriends.splice(index, 1, obj.message)
        // state.onPresenceFriends.push(obj.message)
      }
    // }
    console.log(state.onPresenceFriends, '789787987777777777777777777777777777777777')
  },

  // 修改收到的添加好友请求的信息
  [types.RESET_REVCIEVE_FRIENDS_POST](state, obj) {
    // 先判断该陌生人有没有发起过添加好友的请求
    let tempitem = state.onPresenceFriends.find(f => f.fromJid === obj.jid) || {}
    if (Object.getOwnPropertyNames(tempitem).length) {
      tempitem['read'] = obj.read
      tempitem['agree'] = obj.agree
    }
    console.log('添加好友之后修改的收到添加好友信息的列表信息', state.onPresenceFriends)
  },
    // 删除收到的添加好友请求的信息（一项）
  [types.DELETE_REVCIEVE_FRIENDS_POST](state, jid) {
    // state.onPresenceFriends.splice(index, 1)
    state.onPresenceFriends = state.onPresenceFriends.filter(f => f.fromJid !== jid)
    console.log('删除收到添加好友信息的列表信息', state.onPresenceFriends)
  },
  [types.DELETE_MESSAGE_LIST](state, jid) {
    // let arr = publicjs.cloneObj(state.messageList1)
    state.messageList1 = state.messageList1.filter(f => f['_id'] !== jid)
    // arr.splice(index, 1)
    // state.messageList1.splice(index, 1)
    console.log('删除聊天列表信息*****************************后面检查这里对不对', state.messageList1)
  },
  // 用户登录就初始化收到好友的添加请求
  [types.INIT_REVCIEVE_FRIENDS_POST](state, data) {
    state.onPresenceFriends = data
    console.log('state.onPresenceFriends', state.onPresenceFriends)
  },
  // 用户收到视频语音时候，展现页面标志的修改
  [types.RESET_RECEIVE_AUDIO](state, flag) {
    state.receiveAudio = flag
    console.log(state.receiveAudio, '--->state.receiveAudio')
  },
// 发送语音消息的时候展现出来的界面,标志的修改
  [types.RESET_SHOW_AUDIO](state, flag) {
    state.showAudio = flag
    console.log(state.showAudio, '---->state.showAudio')
  },
  // 收到语音消息的时候展现出来的界面,active标志的修改
  [types.RESET_SHOW_REC](state, flag) {
    state.showRec = flag
    console.log(state.showRec, '---->state.showRes')
  },
  [types.RESET_SHOW_WAITING](state, flag) {
    state.voiceWaiting = flag
    console.log(state.voiceWaiting, '---->state.voiceWaiting')
  },
  /* S=群组 */
  // 用户登录就获取到群组的信息
  [types.SET_GROUP_INFO](state, data) {
    // 1.从数据库里面获得
    // 2.从环信上面获得
    // state.groupInfo = arr
    if (data.flag === 1) {
      console.log(1)
      state.groupInfo = [...data.arr]
    } else if (data.flag === 2) {
      // console.log(2, data.arr, data.arr[0])
      // state.friends = [...data.friends]
      // data.arr.forEach(item => {
        let arr = state.groupInfo.filter(f => f.id === data.arr[0].id)
        // console.log(arr, '999999')
        if (!arr.length) {
          // console.log(3)
          state.groupInfo.push(data.arr[0])
        }
      // })
    } else if (data.flag === 3) {
      let index = state.groupInfo.findIndex(f => f.id === data.arr[0].id)
      if (index !== -1) {
        state.groupInfo.splice(index, 1, data.arr[0])
        console.log(state.groupInfo, '点进去群组的最终版本')
        // 顺便更新当前聊天的的群组对象
        state.currentChatGroup = {...data.arr[0]}
      }
    }
  },
  // 用户受到邀请添加的群--群组数组添加一项
  [types.ADD_GROUP_INFO](state, option) {
    if (option) {
      state.groupInfo.push(option)
    }
  },
  // 用户登录就初始化当前用户的群组聊天信息
  [types.SET_GROUP_MESSAGELIST](state, arr) {
    if (arr.length) {
      state.groupMessageList = [...arr]
    }
  },
  /* E=群组 */
  /* S=标签 */
  // 用户登录就从数据库获取到标签的信息
  [types.SET_LABEL_INFO](state, arr) {
    state.labelInfo = [...arr]
  },
  // 标签数组添加一项
  [types.ADD_LABEL_INFO](state, option) {
    if (option) {
      state.labelInfo.push({...option})
    }
  },
  /* E=标签 */
  [types.RESET_HEAD_ICON](state, url) {
    if (url) {
      // console.log(state.currentLoginUser, 'iiiii')
      state.currentLoginUser.headicon = url
    }
  }
}
